package com.ruoyi.docdraw.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import cn.hutool.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static final int CONNECT_TIMEOUT = 15000;
    private static final int READ_TIMEOUT = 60000;

    public static String postJSON(String url, JSONObject json, Map<String, String> headers) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        try {
            // 创建URL对象
            URL targetUrl = new URL(url);
            conn = (HttpURLConnection) targetUrl.openConnection();

            // 设置请求方法和属性
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);

            // 设置默认请求头
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            conn.setRequestProperty("Accept", "application/json");

            // 添加自定义请求头
            if (headers != null) {
                for (Map.Entry<String, String> header : headers.entrySet()) {
                    conn.setRequestProperty(header.getKey(), header.getValue());
                }
            }

            // 发送请求体
            String jsonString = json.toString();
            try (OutputStream os = conn.getOutputStream()) {
                os.write(jsonString.getBytes("UTF-8"));
                os.flush();
            }

            // 处理响应
            int statusCode = conn.getResponseCode();
            logger.debug("HTTP POST to {} returned status code: {}", url, statusCode);

            StringBuilder response = new StringBuilder();
            if (statusCode >= 200 && statusCode < 300) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }

            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

            logger.trace("Response body: {}", response.toString());
            return response.toString();

        } catch (IOException e) {
            logger.error("HTTP request failed", e);
            throw new Exception("HTTP request failed: " + e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("Error closing reader", e);
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}
